package NG::Gen::Battle::Abilities;
use strict;
use warnings;

use NG::Sys::App;
use Data::Dumper;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(apply_ability);


sub apply_ability {
	my ($dir,$ual,$unit,$log) = @_;
	for my $ua(@{$ual||[]}){
		my $ad = $ua->{ability};
		unless(defined $ad->{count} and defined $ua->{count}){
			app->logger->info("BAD: ",Dumper[$ad,$ua]);
			return;
		}
		if(($ua->{count} || $ua->{rest}) && $ad->{count} <= $ua->{count}){
			my $rv = rand(100);
			#push @$log,["try ability",$dir,$ad->{an},($rv < $ad->{chance}?"success":"fail"),$ad->{count},"from",$ua->{count},$rv,"<",$ad->{chance}];
			if($rv < $ad->{chance}){
				$ad->{sub}($dir,$ua,$ad->{value},$unit,$log);
			}
			$ad->{count}++;
		}
	}
}


# лечит раненого юнита
sub cure {
	my ($dir,$ua,$value,$unit,$log) = @_;
	if(my $r = $unit->{rest}){
		my $need = $unit->{health} - $r;
		my $cure = int($unit->{health} * $value/100);
		if($cure > $need){
			$cure = $need;
		}
		$unit->{rest} += $cure;
		push @$log,["cure",$dir,$ua->{title},$ua->{ability}{count},$ua->{count},$unit->{title},$cure,$r,$unit->{rest}];
	}
}

# повышает кучность
sub target {
	my ($dir,$ua,$value,$unit,$log) = @_;
	my $add = int($unit->{spread} * $value/100);
	($unit->{add_modif}{spread}||=0) += $add;
	push @$log,["target",$dir,$ua->{title},$ua->{ability}{count},$ua->{count},$unit->{title},$add,$unit->{add_modif}{spread}];
}

# понижает уязвимость
sub cover {
	my ($dir,$ua,$value,$unit,$log) = @_;
	my $add = int($unit->{vulner} * $value/100);
	($unit->{add_modif}{vulner}||=0) += $add;
	push @$log,["cover",$dir,$ua->{title},$ua->{ability}{count},$ua->{count},$unit->{title},$add,$unit->{add_modif}{vulner}];
}
sub boost {
	my ($dir,$ua,$value,$unit,$log) = @_;
	if($unit->{current} < $unit->{count}){
		$unit->{current}--;
		$unit->{again} = 1;
		push @$log,["boost",$dir,$ua->{title},$ua->{ability}{count},$ua->{count},$unit->{title}];
	}
}

1;
